package org.srunpass.bitmap.query;

import java.util.Arrays;
import java.util.function.Consumer;

import org.srunpass.bitmap.condition.Condition;
import org.srunpass.bitmap.condition.EqCondition;
import org.srunpass.bitmap.condition.InCondition;
import org.srunpass.bitmap.enums.OperateTypeEnum;
import org.srunpass.bitmap.expression.Expression;

import lombok.Getter;

/**
 * @author srunpass
 * @version Id: QueryWrapper, v 0.1 2025/6/30 09:23 srunpass Exp $
 */
@Getter
public class QueryWrapper {

    private Expression rootExpression;

    public QueryWrapper in(String field, Object... vals) {
        addCondition(new InCondition(field, Arrays.asList(vals)));
        return this;
    }

    public QueryWrapper eq(String field, Object val) {
        addCondition(new EqCondition(field, val));
        return this;
    }

    public QueryWrapper or(Consumer<QueryWrapper> consumer) {
        QueryWrapper nested = new QueryWrapper();
        consumer.accept(nested);
        addExpression(OperateTypeEnum.OR, nested.getRootExpression());
        return this;
    }

    public QueryWrapper and(Consumer<QueryWrapper> consumer) {
        QueryWrapper nested = new QueryWrapper();
        consumer.accept(nested);
        addExpression(OperateTypeEnum.AND, nested.getRootExpression());
        return this;
    }

    private void addCondition(Condition condition) {
        if (rootExpression == null) {
            rootExpression = new Expression(condition);
        } else {
            rootExpression.opt(OperateTypeEnum.AND, new Expression(condition));
        }
    }

    private void addExpression(OperateTypeEnum opt, Expression expression) {
        if (rootExpression == null) {
            rootExpression = expression;
        } else {
            rootExpression.opt(opt, expression);
        }
    }

}
